package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.*;
import com.heima.article.feign.BehaviorFegin;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-23
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    @Autowired
    IApArticleContentService contentService;
    @Autowired
    @Lazy
    private ITemplateService templateService;
//新增文章信息
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {

        ApArticle apArticle=new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
//        首先判断文章是否包含文章id 不包含新增 包含修改
//        新增
        if(dto.getId()==null){
//            保存文章信息
            apArticle.setCreatedTime(new Date());

            this.save(apArticle);
//            保存文章内容
            ApArticleContent entity=new ApArticleContent();
            entity.setArticleId(apArticle.getId());
            entity.setContent(dto.getContent());
            contentService.save(entity);
            // 生成静态html  需要异步处理
            System.out.println(Thread.currentThread().getName() + " 开始调用生成静态html服务...");
            templateService.createHtml(apArticle, dto.getContent());
            System.out.println(Thread.currentThread().getName() + " 生成静态html调用结束");
            return ResponseResult.okResult(apArticle.getId());


        }else {
//            修改文章信息
            this.updateById(apArticle);
//            修改文章内容
            LambdaUpdateWrapper<ApArticleContent> updateWrapper=new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApArticleContent::getArticleId,dto.getId());
            updateWrapper.set(ApArticleContent::getContent,dto.getContent());
            contentService.update(updateWrapper);
            return ResponseResult.okResult(apArticle.getId());


        }

    }

    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int i) {

//        i 1 加载下一页 o加载最新页


        LambdaQueryWrapper<ApArticle> query=new LambdaQueryWrapper<>();
        if(i!=0){
//            根据频道查询
            query.eq(ApArticle::getChannelId,dto.getChannelId());
        }
//        加载下一夜，是就是发布时间小鱼前端最小值
        if(i==1){
            query.lt(ApArticle::getPublishTime,dto.getMinTime());


        }
//        dayu最大值
        if(i==1){
            query.gt(ApArticle::getPublishTime,dto.getMaxTime());
        }
//        下架和删除
        query.eq(ApArticle::getIsDelete,false);
        query.eq(ApArticle::getIsDown,false);
        query.orderByDesc(ApArticle::getCreatedTime);

        IPage<ApArticle> page=new Page<>(1,dto.getSize());
        IPage<ApArticle> iPage = this.page(page, query);


        return ResponseResult.okResult(iPage.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        ApArticle article = this.getById(dto.getArticleId());
        LambdaQueryWrapper<ApArticleContent> query=new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent content = contentService.getOne(query);
        Map<String,Object>map=new HashMap<>();
        map.put("config",article);
        map.put("content",content);
        return ResponseResult.okResult(map);
    }
//文章的收藏
@Autowired
IApCollectionService collectionService;
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {


//        构建一个收藏apCollection
        ApCollection apCollection=new ApCollection();
        User user = AppThreadLocalUtil.get();
        apCollection.setEntryId(user.getUserId());
        apCollection.setArticleId(dto.getArticleId());
        apCollection.setCollectionTime(new Date());
//        查询收藏表
        LambdaQueryWrapper<ApCollection> query=new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId,dto.getArticleId());
        query.eq(ApCollection::getEntryId,user.getUserId());
        ApCollection one = collectionService.getOne(query);
        if(one==null){
            if(dto.getOperation()==0){
                collectionService.save(apCollection);
                sendMessage(dto);



            }

        }else {
            if(dto.getOperation()==1){
                collectionService.remove(query);
                sendMessage(dto);
            }
        }


        return ResponseResult.okResult();
    }

@Autowired
private KafkaTemplate kafkaTemplate;
    @Value("article_behavior")
    private String CollectionTopic;


    //    文章收藏kafka发送
    private void sendMessage(CollectionBehaviorDto dto) {
//        发送消息
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(3);
        message.setArticleId(dto.getArticleId());
        message.setAdd(1);
//        判断是并不是点赞
        if (dto.getOperation() == 1) {
            message.setAdd(-1);

        }
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(CollectionTopic, value);


    }

//加载文章行为记录
//    喜欢不喜欢的
    @Autowired
    private BehaviorFegin behaviorFegin;
//    查询用户关注的
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private IApAuthorService apAuthorService;
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
//        首先初始化dto参数

        Boolean isFollow=false;
        Boolean isCollection=false;
        Boolean isLike=false;
        Boolean isUnlike=false;
        User user = AppThreadLocalUtil.get();
//        远程调用行为微服务查询不喜欢
        UnLikesBehaviorDto unlikeDto=new UnLikesBehaviorDto();
        if (user!=null){
            unlikeDto.setUserId(user.getUserId());
        }else {
            unlikeDto.setEquipmentId(dto.getEquipmentId());
        }
        unlikeDto.setArticleId(dto.getArticleId());


        ResponseResult<ApUnlikesBehavior> unlikes = behaviorFegin.getUnlikes(unlikeDto);
        if (unlikes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUnlikesBehavior unlikesData = unlikes.getData();
            if(unlikesData!=null&&unlikesData.getType()==0){
                isUnlike=true;

            }
        }
//      远程调用行为微服务查询喜欢
        LikesBehaviorDto likesBehaviorDto=new LikesBehaviorDto();
        BeanUtils.copyProperties(unlikeDto,likesBehaviorDto);
        ResponseResult likes = behaviorFegin.getLikes(likesBehaviorDto);
        if(likes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            isLike=true;
        }
//        调用文章看看关没臭美收藏
        LambdaQueryWrapper<ApCollection> query=new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId,dto.getArticleId());
        query.eq(ApCollection::getEntryId,user.getUserId());
        ApCollection one = collectionService.getOne(query);
        if(one!=null){
            isCollection=true;
        }


//         调动用户微服务查询关注


        if(user!=null){
    FollowBehaviorDto userDto=new FollowBehaviorDto();
    ApAuthor author = apAuthorService.getById(dto.getAuthorId());
    userDto.setUserId(user.getUserId());
    userDto.setFollowId(author.getUserId());

            ResponseResult<ApUserFollow> result = userFeign.getFollow(userDto);
            if(result.getCode()==AppHttpCodeEnum.SUCCESS.getCode()){
                ApUserFollow data = result.getData();
                if(data!=null){
                    isFollow=true;
                }
            }

}
        Map<String,Boolean>map=new HashMap<>();
        map.put("isfollow", isFollow);
        map.put("islike", isLike);
        map.put("isunlike", isUnlike);
        map.put("iscollection", isCollection);
        return ResponseResult.okResult(map);
    }


}
